<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    public const HOME = '/home';

    public function boot(): void
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::middleware('api')
                ->as('api.')
                ->prefix('api')
                ->domain(config('custom.api_domain'))
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->group(base_path('routes/web.php'));
        });
    }

    protected function configureRateLimiting(): void
    {
        RateLimiter::for('api', function (Request $request) {
            $unLimitedIp = config('custom.api.exclude_ip');

            if (!$unLimitedIp && !in_array($request->ip(), explode(',', $unLimitedIp))) {
                return $request->user()
                    ? Limit::perMinute(config('custom.api.rate_login'))->by($request->user()->id)
                    : Limit::perMinute(config('custom.api.rate_un_login'))->by($request->ip());
            }
        });
    }
}
